package springboot.demo.shiro.common.util;

import org.apache.commons.codec.digest.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * <p>Project: springboot-demo </p>
 * 
 * <p>Function:  </p>
 * 
 * <p>Description:  </p>
 * 
 * @author weiqiang.li
 * 
 * @date 2018/11/27
 * 
 * @version 1.0
 */
public class PasswordUtil {

    private static SecureRandom secureRandom = new SecureRandom();

    private static final int SALT_LEN = 8;

    private static final String UTF8 = "UTF-8";

    public static String generateSalt() {
        StringBuffer s = new StringBuffer(SALT_LEN);
        for (int j = 0; j < SALT_LEN; j++) {
            s.append(secureRandom.nextInt(10));
        }
        try {
            return Base64.getEncoder().encodeToString(s.toString().getBytes(UTF8));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String encode(String pwd, String salt) {
        return DigestUtils.sha1Hex(DigestUtils.sha1Hex(pwd) + salt);
    }
}
